import React, { useEffect, useMemo, useRef, useState } from "react";
import Content from "./Content/Index";
import ChatForm from "./ChatForm/ChatForm";
import songStore from "@/store/songStore";
import { getHistory, getWebSocket } from "@/api/chatAPi";
import { chatDataItem } from "@/types/chatType";
import { io, Socket } from "socket.io-client";
import { observer } from "mobx-react-lite";
import roomStore from "@/store/roomStore";
import "./Chat.css";

const Chat: React.FC<{ setMenuIndex: Function }> = (props) => {
  const { setMenuIndex } = props;
  const [chatData, setChatData] = useState<chatDataItem[]>([]);
  const [wsData, setWsData] = useState<any>();
  const wsRef = useRef<Socket | null>(null);
  const [tick, setTick] = useState<string>("");
  const [toBottom, setToBottom] = useState(true);

  useEffect(() => {
    getHistory().then((res) => {
      setChatData(res.data?.reverse() ?? []);
    });
    getWebSocket({
      room_id: Number(localStorage.getItem("room_id")),
      room_password: "",
    }).then((res) => {
      if (res.data) {
        setTick(res.data.tick);
      }
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [roomStore.room_id]);

  useEffect(() => {
    let newChatData: chatDataItem[] = [];
    if (wsData) {
      newChatData = [...chatData, wsData];
    } else {
      newChatData = [...chatData];
    }
    if (chatData.length) {
      setChatData(newChatData);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [wsData]);

  useEffect(() => {
    if (tick !== "") {
      if (wsRef.current) {
        wsRef.current.disconnect();
        wsRef.current = null;
      }
      wsRef.current = io(`ws://124.221.181.19:8000?tick=${tick}`, {
        transports: ["websocket"],
      });
      wsRef.current.on("text", (wsResponse) => {
        setWsData(wsResponse);
      });
      wsRef.current.on("playSong", (res) => {
        if (res) {
          songStore.setSongInfo(res);
        }
      });
      setToBottom(true);
    }
  }, [tick]);

  //缓存组件，防止state修改，重复渲染
  const Memo = useMemo(() => {
    return (
      <>
        <Content
          chatData={chatData}
          toBottom={toBottom}
          setToBottom={setToBottom}
        />
      </>
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [chatData]);

  return (
    <div className={"chat"} onClick={() => setMenuIndex(0)}>
      {Memo}
      <ChatForm setToBottom={setToBottom} />
    </div>
  );
};

export default observer(Chat);
